package com.cw.lang.validator.config;

import java.util.Locale;

import org.hibernate.validator.messageinterpolation.ResourceBundleMessageInterpolator;

/**
 * @author chenw
 * @version $$Id: LocalResourceBundleMessageInterpolator.java, v 0.1 2018/9/20 下午5:26 chenw Exp $$
 */
public class LocalResourceBundleMessageInterpolator extends ResourceBundleMessageInterpolator {

    /**
     * 校验枚举message方法的方法名
     */
    private static final String VALIDATOR_ANNOTATION_MESSAGE_METHOD_NAME = "message";

    /**
     * 默认message的前缀
     */
    private static final String DEFAULT_MESSAGE_PREFIX = "{";

    /**
     * 默认message的后缀
     */
    private static final String DEFAULT_MESSAGE_SUFFIX = "}";

    /**
     * 类路径的连接点
     */
    private static final String PERIOD = ".";

    /**
     * 本地message的前缀
     */
    private static final String LOCAL_MESSAGE_PREFIX = "(";

    /**
     * 本地message的后缀
     */
    private static final String LOCAL_MESSAGE_SUFFIX = ")";

    @Override
    public String interpolate(String message, Context context) {
        return this.interpolate(message, context, Locale.getDefault());
    }

    @Override
    public String interpolate(String message, Context context, Locale locale) {
        String defaultMessageCode = getDefaultMessageCode(context);
        if (defaultMessageCode.equals(message)) {
            return super.interpolate(defaultMessageCode, context, Locale.getDefault());
        } else {
            return generateLocalMessage(super.interpolate(defaultMessageCode, context, locale), message);
        }
    }

    /**
     * 获取注解message方法的默认返回参数
     *
     * @param context 上下文
     * @return 注解message方法的默认返回参数
     */
    private String getDefaultMessageCode(Context context) {
        String clazzPath = context.getConstraintDescriptor().getAnnotation().annotationType().getCanonicalName();
        return DEFAULT_MESSAGE_PREFIX + clazzPath + PERIOD + VALIDATOR_ANNOTATION_MESSAGE_METHOD_NAME
            + DEFAULT_MESSAGE_SUFFIX;
    }

    /**
     * 组装对外暴露的消息描述
     *
     * @param defaultMessage 默认消息
     * @param localMessage 业务侧添加的业务消息
     * @return 对外暴露的消息描述
     */
    private String generateLocalMessage(String defaultMessage, String localMessage) {
        return LOCAL_MESSAGE_PREFIX + defaultMessage + LOCAL_MESSAGE_SUFFIX + localMessage;
    }
}
